package com.bjsxt.service.impl;

import com.bjsxt.domain.OrderTbl;
import com.bjsxt.mapper.OrderTblMapper;
import com.bjsxt.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderTblMapper orderTblMapper ;

    @Autowired
    private AccountServiceApi accountServiceApi ;

    private static Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class) ;

    @Transactional
    @Override
    public OrderTbl createOrder(String userId, String productNo, int count) {
        logger.info("开始创建一个订单，用户为{},商品为{}，数量为{}",userId,productNo,count);
        // 1 扣减用户的余额 account-service - >rpc
        int money = cal(productNo,count) ;
        ResponseEntity<Void> responseEntity = accountServiceApi.debit(userId, money);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new RuntimeException("远程扣减用户的余额失败") ;
        }
        //2 写本地的订单表
        OrderTbl orderTbl = new OrderTbl();
        orderTbl.setUserId(userId);
        orderTbl.setCommodityCode(productNo);
        orderTbl.setCount(count);
        orderTblMapper.insert(orderTbl) ;

        logger.info("创建订单成功，用户为{}，商品为{},数量{}",userId,productNo,count);
        return orderTbl;
    }

    /**
     * 计算商品的总价格
     * @param productNo
     * @param count
     * @return
     */
    private int cal(String productNo, int count) {
        //我们的数据库里面非常简单，没有商品的表
        int money = 0  ;
        if("HUAWEI_0001".equals(productNo)){
            money = 2000 ;
        }else if("XIAOMI_002".equals("productNo")){
            money = 1000 ;
        }else {
            money = 9999 ;
        }
        return money * count ;
    }
}
